import { ApiuserPatientVotePost } from "../../../../api/index"
import { debounce } from "../../../../utils/index"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    btnLoading: false,
    info: {},
    list: [],
    answerObj: {},
    errorObj: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const data = wx.getStorageSync('satisfaction')
    if(!data || !Array.isArray(data.vote_question)) return
    const list = data.vote_question
    const answerObj = list.reduce((obj,item) => {
      obj[item.id] = item.type === "评分类" ? 0 : ""
      return obj
    },{})
    this.setData({
      list,
      answerObj,
      info: {
        id: data.id,
        name: data.name,
        questionnaire_id: data.questionnaire_id,
        survey_id: data.survey_id
      }
    })
  },

  onUnload() {
    wx.removeStorage({
      key: 'satisfaction',
    })
  },

  onChange(e) {
    const id = e.currentTarget.dataset.id
    const value = e.detail.value
    if(value !== this.data.answerObj[id]){
      this.setData({
        [`answerObj.${id}`]: value,
        [`errorObj.${id}`]: ""
      })
    }
  },


  onSubmit: debounce(function () {
    const answerObj = this.data.answerObj
    let once = null, errorObj = {}
    this.data.list.forEach(item => {
      if(!answerObj[item.id]){
        errorObj[item.id] = item.type === "评分类" ? '请对该项目打分' : '请输入您的建议'
        if(!once) once = item.id
      }
    })
    if(once) {
      wx.pageScrollTo({
        offsetTop: -110,
        selector: `.item_cell_${once}`,
      })
      wx.showToast({
        title: '您还有题目未填写！',
        icon: "none"
      })
      this.setData({
        errorObj,
      })
      return
    }

    this.setData({
      btnLoading: true
    })

    ApiuserPatientVotePost({vote_id: this.data.info.id,answer:answerObj }).then(res => {
      wx.showModal({
        title: "感谢您的填写！",
        showCancel: false,
        confirmText: "返回",
        success() {
          wx.navigateBack()
        }
      })
    }).finally(_=>{
      this.setData({
        btnLoading: false
      })
    })
  },500,true) ,
  /**
   * 生命周期函数--监听页面初次渲染完成
   */

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})